#!/usr/bin/env node

/**
 * 诊断预约列表接口问题
 * 直接调用服务层方法，模拟前端调用
 */

import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..')

async function main() {
  console.log('='.repeat(60))
  console.log('诊断预约列表接口')
  console.log('='.repeat(60))
  console.log()

  // 初始化数据库 - 使用生产环境路径
  const { PrismaClient } = await import('@prisma/client')
  
  // 尝试多个可能的数据库路径（优先使用生产环境）
  const possibleDbPaths = []
  
  // 如果是Windows，优先使用生产环境路径
  if (process.platform === 'win32') {
    // 优先使用生产环境实际路径
    possibleDbPaths.push('C:\\Users\\Administrator\\AppData\\Roaming\\AutoTools\\data\\app.db')
    
    const appData = process.env.APPDATA || process.env.LOCALAPPDATA
    if (appData) {
      possibleDbPaths.push(join(appData, 'AutoTools', 'data', 'app.db'))
      possibleDbPaths.push(join(appData, 'auto-tools', 'data', 'app.db'))
    }
  }
  
  // 最后尝试开发环境路径
  possibleDbPaths.push(join(projectRoot, 'prisma', 'data', 'app.db'))
  
  let dbPath = null
  for (const path of possibleDbPaths) {
    if (existsSync(path)) {
      dbPath = path
      console.log(`找到数据库文件: ${dbPath}`)
      break
    }
  }
  
  if (!dbPath) {
    console.error('❌ 未找到数据库文件，尝试了以下路径:')
    possibleDbPaths.forEach(p => console.error(`  - ${p}`))
    process.exit(1)
  }
  
  const dbUrl = `file:${dbPath.replace(/\\/g, '/')}`
  process.env.DATABASE_URL = dbUrl

  const prisma = new PrismaClient({
    datasources: {
      db: { url: dbUrl },
    },
  })

  try {
    await prisma.$executeRawUnsafe('PRAGMA journal_mode=WAL;')
  }
  catch {}

  // 直接测试服务层逻辑
  console.log('模拟前端调用场景:')
  console.log('----------------------------------------')
  
  // 场景1: 前端 filters = { is_placeholder: undefined }
  console.log('\n场景1: 前端传递 is_placeholder: undefined')
  const frontendFilters1 = {
    appointment_status: [],
    is_placeholder: undefined,
  }
  // 模拟 JSON.stringify 的行为
  const serialized1 = JSON.parse(JSON.stringify(frontendFilters1))
  console.log('序列化后:', JSON.stringify(serialized1))
  
  // 模拟后端处理逻辑
  const where1 = {}
  if (serialized1.is_placeholder !== undefined) {
    where1.is_placeholder = serialized1.is_placeholder
    console.log('⚠️  添加了 is_placeholder 过滤条件')
  }
  else {
    console.log('✅ 未添加 is_placeholder 过滤条件（应该返回所有数据）')
  }
  
  const count1 = await prisma.appointment_management.count({ where: where1 })
  console.log(`查询结果: ${count1} 条`)
  console.log()

  // 场景2: 检查数据库中实际的数据分布
  console.log('数据库实际数据分布:')
  console.log('----------------------------------------')
  const total = await prisma.appointment_management.count()
  const placeholderTrue = await prisma.$queryRawUnsafe('SELECT COUNT(*) as count FROM appointment_management WHERE is_placeholder = 1;')
  const placeholderFalse = await prisma.$queryRawUnsafe('SELECT COUNT(*) as count FROM appointment_management WHERE is_placeholder = 0;')
  const placeholderNull = await prisma.$queryRawUnsafe('SELECT COUNT(*) as count FROM appointment_management WHERE is_placeholder IS NULL;')
  
  const countTrue = Array.isArray(placeholderTrue) && placeholderTrue[0] ? Number(placeholderTrue[0].count) : 0
  const countFalse = Array.isArray(placeholderFalse) && placeholderFalse[0] ? Number(placeholderFalse[0].count) : 0
  const countNull = Array.isArray(placeholderNull) && placeholderNull[0] ? Number(placeholderNull[0].count) : 0
  
  console.log(`总记录数: ${total}`)
  console.log(`is_placeholder = true (占号): ${countTrue} 条`)
  console.log(`is_placeholder = false (普通): ${countFalse} 条`)
  console.log(`is_placeholder = null: ${countNull} 条`)
  console.log(`验证: ${countTrue + countFalse + countNull} = ${total} (应该相等)`)
  console.log()

  // 场景3: 检查是否有其他隐藏的过滤条件
  console.log('检查其他可能的过滤条件:')
  console.log('----------------------------------------')
  const emptyWhere = {}
  const countEmpty = await prisma.appointment_management.count({ where: emptyWhere })
  console.log(`空 where 条件查询: ${countEmpty} 条`)
  
  if (countEmpty !== total) {
    console.log('⚠️  发现问题：空where条件查询结果与总数不一致！')
  }
  else {
    console.log('✅ 空where条件查询正常')
  }
  console.log()

  // 场景4: 检查前几条记录的实际 is_placeholder 值
  console.log('检查前10条记录的 is_placeholder 值:')
  console.log('----------------------------------------')
  const sampleRecords = await prisma.$queryRawUnsafe(`
    SELECT id, sequence_number, full_name, is_placeholder, appointment_status 
    FROM appointment_management 
    LIMIT 10;
  `)
  if (Array.isArray(sampleRecords)) {
    sampleRecords.forEach((r, idx) => {
      console.log(`  ${idx + 1}. ID=${r.id}, 序号=${r.sequence_number}, 姓名=${r.full_name}, is_placeholder=${r.is_placeholder}, 状态=${r.appointment_status}`)
    })
  }
  console.log()

  console.log('='.repeat(60))
  console.log('诊断结论:')
  console.log('='.repeat(60))
  if (count1 === total) {
    console.log('✅ 接口逻辑正常：不传递is_placeholder时返回所有数据')
    console.log(`   返回: ${count1} 条，数据库总数: ${total} 条`)
    console.log('\n💡 可能的原因:')
    console.log('   1. UI界面中用户手动选择了"占号数据"筛选')
    console.log('   2. UI界面默认显示了占号管理页面')
    console.log('   3. 前端有其他地方设置了默认过滤条件')
  }
  else if (count1 === countTrue) {
    console.log('⚠️  发现问题：接口默认返回了占号数据！')
    console.log(`   返回: ${count1} 条，占号数据: ${countTrue} 条`)
    console.log('\n💡 需要检查:')
    console.log('   1. Prisma schema 中 is_placeholder 字段的定义')
    console.log('   2. 是否有默认值或约束导致查询结果异常')
  }
  else {
    console.log('⚠️  异常情况：返回的数据量不符合预期')
    console.log(`   返回: ${count1} 条，总数据: ${total} 条，占号: ${countTrue} 条`)
  }
  console.log('='.repeat(60))
}

main().catch((e) => {
  console.error('脚本执行失败:', e)
  process.exit(1)
})

